import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { ListView,Toast } from 'antd-mobile';
import PubSub from 'pubsub-js';
import { searchAudio, getUuid, convetAudios,isContrainAlbum } from '../utils.js';
import AudioItem from '../components/AudioItem';
import { BAIDU_CATEGORY_ID} from '../config';

// 搜索音频列表
class SearchAudioList extends Component {
    constructor(props, context) {
        super(props, context);
        const ds = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        })
        this.handleRemotePlay = this.handleRemotePlay.bind(this)
        let audios = this.props.audio_list
        this.state = {
            audios: audios,
            dataSource: ds.cloneWithRows(audios),
            height: document.documentElement.clientHeight, // 高度
            keywords: this.props.keywords,
            isLoading: true,
            hasMore: true,
            page: 2
        }
        this.filterAlbums = []
    }

    componentDidMount() {
        let hei = document.documentElement.clientHeight - ReactDOM.findDOMNode(this.lv).parentNode.offsetTop
        this.setState({
            height: hei,
        });

        this.checkAlbums = setInterval(() => {
            if (this.filterAlbums.length === 0) {
                this.getFilterAlbum();
            }
        }, 2000);
    }

    getFilterAlbum(){
        const filterAlbumString = localStorage.getItem('filter_album');
        if (filterAlbumString) {
            this.filterAlbums = JSON.parse(filterAlbumString);
        }
    }


    componentWillReceiveProps(nextProps) {
        this.setState({
            audios: nextProps.audio_list,
            keywords: nextProps.keywords,
            page:2,
            dataSource: this.state.dataSource.cloneWithRows(nextProps.audio_list),
        });
    }


    fetch() {
        searchAudio(getUuid(), this.state.keywords, this.state.page, (function (result) {
            if (result.errcode === 0) {
                let audioList = convetAudios(result.data)
                if (audioList.length > 0) {
                    let newAudios = this.state.audios.concat(audioList)
                    let page = this.state.page + 1
                    this.setState({
                        audios: newAudios,
                        dataSource: this.state.dataSource.cloneWithRows(newAudios),
                        hasMore: audioList.length >= 20,
                        isLoading: false,
                        page: page
                    });
                } else {
                    this.setState({ isLoading: false, hasMore: false });
                }
            } else {
                this.setState({ isLoading: false, });
            }
        }).bind(this))
    }

    handleRemotePlay(audio) {
        if (isContrainAlbum(this.filterAlbums, audio)) {
            PubSub.publish('remotePlay', { category_id: BAIDU_CATEGORY_ID, audio: audio,audioList:[] });
        }else {
            Toast.show('该专辑尚未购买',1,false);
        }
    }

    onEndReached = (event) => {
        if (this.state.isLoading && !this.state.hasMore) {
            return;
        }
        this.setState({ isLoading: true });
        this.fetch()
    }

    componentWillUnmount(){
        clearInterval(this.checkAlbums);
    }

    render() {
        let row = (rowData, sectionID, rowID) => {
            return (
                <div key={rowID} >
                    <AudioItem
                        index={parseInt(rowID, 10)}
                        audio={rowData}
                        device_id={this.props.device_id}
                        hiddenRight={true}
                        handleRemotePlay={this.handleRemotePlay} />
                </div>
            );
        };

        return (
            <ListView
                ref={el => this.lv = el}
                className="am-list"
                dataSource={this.state.dataSource}
                renderFooter={() => (
                    <div style={footerStyles}>
                        {this.state.hasMore === true ? "正在加载内容..." : '没有更多内容了~'}
                    </div>)}
                renderRow={row}
                style={{
                    height: this.state.height,
                    overflow: 'auto',
                }}
                initialListSize={21}
                pageSize={20}
                scrollRenderAheadDistance={500}
                onEndReached={this.onEndReached}
                onEndReachedThreshold={20}
            />
        );
    }
}


export default SearchAudioList;

const footerStyles = {
    paddingBottom: 40,
    marginBottom: 20,
    textAlign: 'center',
    fontSize: '13px',
}